﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using WebFile.Models;
using System.Web;
using System.IO;
using System.Text.Json;
using SQLiteCoreDB;
using SQLiteCoreDB.Models;
using Microsoft.AspNetCore.Authorization;
using SQLiteCoreDB.Context;

namespace WebFile.Controllers
{

    public class ChatController : Controller
    {
        private ChartApp _db = SL.db;

        public ChatController()
        {

        }

        // GET: Chat
        public ActionResult Add([FromBody] ChatUser user)
        {

            List<ChatUser> userList = _db.ChatUser.ToList();
            if (userList != null)
            {
                if (ModelState.IsValid && user.Text != null)
                {
                    user.Name = LoginMode.username;
                    user.Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    _db.Add(user);
                }
                else
                {
                    return Json(new Result("失败"));
                }
                if (userList.Count > 400)
                {
                    _db.RemoveRange(0, 100);
                }
            }


            try
            {
                // 将更新后的 users 对象转换为 JSON 字符串
                _db.SaveChanges();
            }
            catch (Exception e)
            {
                return Json(new Result("失败" + e.Message));
            }
            return Json(new Result("发送成功", 1));
        }


    }



}
